import { useCallback, useEffect, useState } from 'react';

import { Button, ButtonVariants } from '@/shared/ui/Button';
import { useIsClient, useWindowSize } from 'usehooks-ts';

import cs from './ScrollTop.module.scss';
/* eslint-disable max-len */
const Icon = () => (
  <svg fill="none" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
    <path
      d="M11.2897 9.04921L7.0497 13.2892C6.95598 13.3822 6.88158 13.4928 6.83081 13.6146C6.78004 13.7365 6.75391 13.8672 6.75391 13.9992C6.75391 14.1312 6.78004 14.2619 6.83081 14.3838C6.88158 14.5056 6.95598 14.6162 7.0497 14.7092C7.23707 14.8955 7.49052 15 7.7547 15C8.01889 15 8.27234 14.8955 8.4597 14.7092L11.9997 11.1692L15.5397 14.7092C15.7271 14.8955 15.9805 15 16.2447 15C16.5089 15 16.7623 14.8955 16.9497 14.7092C17.0424 14.6158 17.1157 14.505 17.1655 14.3831C17.2152 14.2613 17.2405 14.1308 17.2397 13.9992C17.2405 13.8676 17.2152 13.7371 17.1655 13.6153C17.1157 13.4935 17.0424 13.3826 16.9497 13.2892L12.7097 9.04921C12.6167 8.95548 12.5061 8.88109 12.3843 8.83032C12.2624 8.77955 12.1317 8.75341 11.9997 8.75341C11.8677 8.75341 11.737 8.77955 11.6151 8.83032C11.4933 8.88109 11.3827 8.95548 11.2897 9.04921Z"
      fill="black"
    />
  </svg>
);
export const ScrollTop = () => {
  const isClient = useIsClient();
  const [scrollY, setScrollY] = useState(0);
  const { height } = useWindowSize();
  const onScroll = useCallback(() => {
    setScrollY(window.scrollY);
  }, []);
  useEffect(() => {
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      window.removeEventListener('scroll', onScroll);
    };
  }, []);
  const handleClick = () => {
    const nav = document.getElementById('page-nav');
    if (!nav) return;
    nav.scrollIntoView();
  };
  if (!isClient || scrollY < height) return <></>;
  return (
    <Button className={cs.scroll} onClick={handleClick} variant={ButtonVariants.Icon}>
      <Icon />
    </Button>
  );
};
